﻿using ArmyCreator;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Windows.Storage;

namespace WebCalls
{
    public class Caller
    {
        private Uri baseUri;
        private string result;
        private string completeRelativeUri;

        public Caller()
        {
            this.baseUri = new Uri(Urls.HOST);
            this.result = null;
        }

        private Uri getCompleteUri()
        {
            Uri uri = new Uri(this.baseUri, completeRelativeUri);
            return uri;
        }

        private string buildRelativeUri(string relativeUri, Dictionary<string, object> parameters)
        {
            string completeRelativeUri = relativeUri;
            string separator = "?";

            foreach (var key in parameters.Keys)
            {
                completeRelativeUri += separator + key + "=" + parameters[key];
                separator = "&";
            }

            return completeRelativeUri;
        }

        public async Task<string> Call(string relativeUri, Dictionary<string, object> parameters)
        {
            this.completeRelativeUri = buildRelativeUri(relativeUri, parameters);

            HttpClient client = new HttpClient();
            client.Timeout = TimeSpan.FromMilliseconds(5000);

            try
            {
                Uri completeUri = getCompleteUri();
                this.result = await client.GetStringAsync(completeUri);
            }
            catch (HttpRequestException) { }
            catch (TimeoutException) { }
            catch (Exception) {/* Mode cache */ }

            return this.result;
        }
    }
}
